/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package stock.tools.extractor;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import stock.config.AppConfig;

/**
 *
 * @author peter
 */
public class IpoPriceExtractor {

    public static void main(String[] args) throws Exception {
        IpoPriceExtractor ext = new IpoPriceExtractor();

        File dir = new File(AppConfig.DATA_DIR + "\\SZF10");
        File xls = new File(AppConfig.DATA_DIR + "\\a_sz.xls");
        File out = new File(AppConfig.DATA_DIR + "\\out.xls");

        Workbook wb = Workbook.getWorkbook(xls);
        Sheet sheet = wb.getSheet(0);

        WritableWorkbook wbOut = Workbook.createWorkbook(out);
        WritableSheet sheetOut = wbOut.createSheet("sz", 0);

        int cols = sheet.getColumns();
        int rows = sheet.getRows();

        for (int i=0; i<rows; ++i) {
            for (int j=0; j<cols; ++j) {  // 复制原有列
                Cell cell = sheet.getCell(j, i);  // j列，i行
                Label label = new Label(j, i, cell.getContents());
                sheetOut.addCell(label);
            }

            // 添加新列
            String price = "";
            if (i == 0) {
                price = "发行价格";
            } else {
                Cell cell = sheet.getCell(0, i);  // 获得股票代码
                File txt = new File(dir, cell.getContents()+".Txt");
                if (txt.exists()) {
                    System.out.println("正在获取价格 ..." + txt.getName());
                    price = ext.extractPrice(txt);
                }
            }
            Label label = new Label(cols, i, price);
            sheetOut.addCell(label);
        }

        wbOut.write();
        wbOut.close();
        wb.close();
    }

    /**
     * 从文件提取发行价格，如果提取不到，返回空字符串
     * @param file
     * @return
     * @throws FileNotFoundException
     */
    private String extractPrice(File file) throws Exception {
        Scanner in = new Scanner(file, "gbk");   // 需要指明字符集

        String price = "";
        while (in.hasNextLine()) {
            String line = in.nextLine();
            if (line.startsWith("发行价格")) {
                StringBuilder sb = new StringBuilder(line);
                int i = sb.indexOf("│");
                int j = sb.indexOf("│", i+1);
                if (j > i) {
                    price = sb.substring(i+1, j).trim();
                }
            }
        }
        in.close();
        return price;
    }
}
